package com.example.filedemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yanzhenjie.permission.AndPermission;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private ImageView ivImage;
    private ImageView ivImage2;
    private Button button2;
    private TextView textView;
    private TextView textView2;
    private static final int REQUEST_PICK_IMAGE = 10086;

    private String realPathFromUri; //上传的图片的原图地址
    private String fileName; //文件名

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String path = msg.getData().getString("path");
                textView.setText(path);
                Bitmap bm = BitmapFactory.decodeFile(path);
                ivImage2.setImageBitmap(bm);
//                File file = new File(path);
//                DebugLog.d(DebugLog.LOGHsc + file.getAbsolutePath() + " ---- " + file.exists());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.btn_switch);
        ivImage = findViewById(R.id.iv_iamge);
        ivImage2 = findViewById(R.id.iv_iamge2);
        button2 = findViewById(R.id.btn_creat);
        textView = findViewById(R.id.tv_attar);
        textView2 = findViewById(R.id.tv_attar2);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(realPathFromUri)) {
                    ToastUtil.toastShortContent(MainActivity.this, "请先选择文件");
                    return;
                }
                File file = new File(realPathFromUri);
                textView2.setText(realPathFromUri);
                DebugLog.d(DebugLog.LOGHsc + file.getAbsolutePath() + " ---- " + file.exists());
                //开始压缩
                CompressFileUtils.getInstance().compressFile(MainActivity.this, realPathFromUri, fileName, FileUtil.createFileDar().getAbsolutePath(), handler);
//                textView.setText();

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PICK_IMAGE:
                    if (data != null) {
                        realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        fileName = realPathFromUri.substring(realPathFromUri.lastIndexOf("/") + 1, realPathFromUri.length());
                        showImage(realPathFromUri);
                        DebugLog.d(DebugLog.LOGHsc + " realPathFromUri " + realPathFromUri);
                    } else {
                        ToastUtil.toastShortContent(this, "图片损坏，请重新选择");
                    }

                    break;
            }
        }
    }

    /**
     * 请求权限
     */
    private void requestPermission() {
        AndPermission.with(this)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                // 准备方法，和 okhttp 的拦截器一样，在请求权限之前先运行改方法，已经拥有权限不会触发该方法
                .rationale((context, permissions, executor) -> {
                    // 此处可以选择显示提示弹窗
                    executor.execute();
                })
                // 用户给权限了
                .onGranted(permissions ->
//                        ToastUtil.toastShortContent(MainActivity.this,getString(R.string.give))
                                getImage()
                )
                // 用户拒绝权限，包括不再显示权限弹窗也在此列
                .onDenied(permissions -> {
                    // 判断用户是不是不再显示权限弹窗了，若不再显示的话进入权限设置页
                    if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions)) {
                        // 打开权限设置页
                        ToastUtil.toastShortContent(MainActivity.this, "请设置读写权限");
                        AndPermission.permissionSetting(MainActivity.this).execute();
                        return;
                    }
                }).start();
    }

    //加载图片
    private void showImage(String imaePath) {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        ivImage.setImageBitmap(bm);
    }

    /**
     * 获取图片
     */
    private void getImage() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    REQUEST_PICK_IMAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
        }
    }
}
